import json
from flask import Flask, request, jsonify, render_template, session
from datetime import datetime
import uuid
import os
from functools import wraps
from werkzeug.utils import secure_filename

app = Flask(__name__)
DATA_FILE = 'comments.json'  # 存储文件路径
app.secret_key = 'your_secret_key_here'  # 用于加密 session 的密钥

app.config['UPLOAD_FOLDER'] = 'static/uploads'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB限制
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'bmp'}

# 确保上传目录存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)


def load_data():
    """从文件加载评论数据"""
    if os.path.exists(DATA_FILE):
        with open(DATA_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    return {"comments": []}  # 初始化空数据

def save_data(data):
    """保存评论数据到文件"""
    with open(DATA_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

# 登录检查装饰器
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'username' not in session:
            return jsonify({"error": "Login required"}), 401
        return f(*args, **kwargs)
    return decorated_function

# 加载初始数据
raw_data = load_data()
comments_db = raw_data.get("comments", [])  # 确保从根节点开始

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/')
def home():
    return render_template('index.html')

@app.route('/api/login', methods=['POST'])
def login():
    data = request.get_json()
    if not data or 'username' not in data:
        return jsonify({"error": "Username required"}), 400
    
    session['username'] = data['username']
    return jsonify({"message": "Login successful"}), 200

@app.route('/api/logout', methods=['POST'])
def logout():
    session.pop('username', None)
    return jsonify({"message": "Logout successful"}), 200

@app.route('/api/comments', methods=['GET'])
def get_comments():
    # 只返回顶级评论（非回复）
    top_level = [c for c in comments_db if 'parent_id' not in c]
    return jsonify(top_level)

@app.route('/api/comments', methods=['POST'])
@login_required
def post_comment():
    data = request.get_json()
    if not data or 'content' not in data:
        return jsonify({"error": "Missing required fields"}), 400
    
    new_id = str(uuid.uuid4())
    new_comment = {
    'id': new_id,
    'author': session['username'],
    'content': data['content'],
    'timestamp': datetime.now().isoformat(),
    'likes': 0,
    'replies': [],
    'images': data.get('images', [])  # 添加图片字段
}
    comments_db.append(new_comment)
    save_data({"comments": comments_db})
    return jsonify(new_comment), 201

@app.route('/api/comments/<string:parent_id>/replies', methods=['GET'])
def get_replies(parent_id):
    # 查找指定父评论的回复
    parent_comment = next((c for c in comments_db if c['id'] == parent_id), None)
    if not parent_comment:
        return jsonify({"error": "Parent comment not found"}), 404
    return jsonify(parent_comment['replies'])

@app.route('/api/comments/<string:parent_id>/replies', methods=['POST'])
@login_required
def post_reply(parent_id):
    parent_comment = next((c for c in comments_db if c['id'] == parent_id), None)
    if not parent_comment:
        return jsonify({"error": "Parent comment not found"}), 404
    
    data = request.get_json()
    if not data or 'content' not in data:
        return jsonify({"error": "Missing required field: content"}), 400
    
    reply_id = str(uuid.uuid4())
    reply = {
        'id': reply_id,
        'author': session['username'],
        'content': data['content'],
        'timestamp': datetime.now().isoformat(),
        'likes': 0,
        'replies': [],
        'images': data.get('images', [])  # 添加图片字段
    }
    parent_comment['replies'].append(reply)
    save_data({"comments": comments_db})
    return jsonify(reply), 201

@app.route('/api/comments/<string:comment_id>', methods=['PUT'])
@login_required
def update_comment(comment_id):
    # 查找评论
    comment = next((c for c in comments_db if c['id'] == comment_id), None)
    if not comment:
        return jsonify({"error": "Comment not found"}), 404
    
    # 检查是否是评论作者
    if comment['author'] != session['username']:
        return jsonify({"error": "You can only edit your own comments"}), 403
    
    data = request.get_json()
    if not data or 'content' not in data:
        return jsonify({"error": "Missing content"}), 400
    
    comment['content'] = data['content']
    save_data({"comments": comments_db})
    return jsonify(comment), 200

@app.route('/api/comments/<string:comment_id>', methods=['DELETE'])
@login_required
def delete_comment(comment_id):
    global comments_db
    
    # 查找评论
    comment = next((c for c in comments_db if c['id'] == comment_id), None)
    if not comment:
        return jsonify({"error": "Comment not found"}), 404
    
    # 检查是否是评论作者
    if comment['author'] != session['username']:
        return jsonify({"error": "You can only delete your own comments"}), 403
    
    # 删除评论
    comments_db = [c for c in comments_db if c['id'] != comment_id]
    save_data({"comments": comments_db})
    
    return jsonify({"message": "Comment deleted"}), 200

@app.route('/api/current_user')
def current_user():
    return jsonify({"username": session.get('username')})

@app.route('/api/upload', methods=['POST'])
@login_required
def upload_image():
    if 'file' not in request.files:
        return jsonify({"error": "No file provided"}), 400
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "No file selected"}), 400
    
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        # 添加时间戳避免文件名冲突
        unique_filename = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{filename}"
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
        file.save(filepath)
        
        return jsonify({
            "message": "File uploaded successfully",
            "filename": unique_filename,
            "url": f"/static/uploads/{unique_filename}"
        }), 200
    
    return jsonify({"error": "File type not allowed"}), 400

if __name__ == '__main__':
    app.run(debug=True)
